package com.ruoyi.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.Lab;
import com.ruoyi.business.mapper.LabMapper;
import com.ruoyi.business.service.ILabService;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 实验台Service业务层处理
 * 
 * @author qiancheng
 * @date 2025-06-13
 */
@Service
public class LabServiceImpl extends ServiceImpl<LabMapper, Lab> implements ILabService
{
    @Autowired
    private LabMapper labMapper;


    /**
     * 查询实验台
     * 
     * @param id 实验台主键
     * @return 实验台
     */
    @Override
    public Lab selectLabById(Long id)
    {
        return labMapper.selectLabById(id);
    }

    /**
     * 实验平台管理->>试验台运行状态->>查询实验台列表
     * 
     * @param lab 实验台
     * @return 实验台
     */
    @Override
    public List<Lab> selectLabList(Lab lab) {
        List<Lab> labs = labMapper.selectLabList(lab);
        List<Lab> labCountList = baseMapper.selectLabCount();

        // 将 labCountList 按 ID 分组为 Map<Long, Lab>
        Map<Long, Lab> labCountMap = labCountList.stream()
                .collect(Collectors.toMap(
                        Lab::getId,
                        Function.identity(),
                        (existing, replacement) -> existing
                ));

        labs.forEach(labItem -> {
            Lab countData = labCountMap.get(labItem.getId());
            if (countData != null) {
                labItem.setSumCount(countData.getSumCount());
                labItem.setIngCount(countData.getIngCount());
            }
        });

        return labs;
    }

    /**
     * 新增实验台
     * 
     * @param lab 实验台
     * @return 结果
     */
    @Override
    public int insertLab(Lab lab)
    {
        lab.setCreateTime(DateUtils.getNowDate());
        return labMapper.insert(lab);
    }

    /**
     * 修改实验台
     * 
     * @param lab 实验台
     * @return 结果
     */
    @Override
    public int updateLab(Lab lab)
    {
        lab.setUpdateTime(DateUtils.getNowDate());
        return labMapper.updateLab(lab);
    }

    /**
     * 批量删除实验台
     * 
     * @param ids 需要删除的实验台主键
     * @return 结果
     */
    @Override
    public int deleteLabByIds(Long[] ids)
    {
        return labMapper.deleteLabByIds(ids);
    }

    /**
     * 删除实验台信息
     * 
     * @param id 实验台主键
     * @return 结果
     */
    @Override
    public int deleteLabById(Long id)
    {
        return labMapper.deleteLabById(id);
    }
}
